﻿using System;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Component
{
    public class CameraController : MonoBehaviour
    {
        [SerializeField] private float minSize;
        [SerializeField] private float maxSize;

        private Vector3 bounds;
        private Vector3 boundsPosition;

        private Transform cameraTransform;
        private bool dragging;
        public bool Draggable { get; set; } = false;
        
        private void Start()
        {
            cameraTransform = Camera.main.transform;
            boundsPosition = transform.position;
            bounds = Vector3.zero;
        }

        private void Update()
        {
            if(!Draggable) return;
            
            DragCamera();
        }

        public void SetBounds(Vector3 b)
        {
            bounds = b;
            boundsPosition = transform.position;
            Draggable = true;
        }

        private LTDescr desc;
        private Vector3 current;
        private void DragCamera()
        {
            if (Input.GetMouseButton(0))
            {
                desc?.reset();
                Vector3 original = cameraTransform.position;
                Vector3 newPosition = original - (cameraTransform.right * Input.GetAxis("Mouse X") + 
                                                cameraTransform.up * Input.GetAxis("Mouse Y")) * (1 * Time.timeScale);
                newPosition = new Vector3(
                    Mathf.Clamp(newPosition.x, boundsPosition.x - bounds.x, boundsPosition.x + bounds.x),
                    Mathf.Clamp(newPosition.y, boundsPosition.y - bounds.y, boundsPosition.y + bounds.y),
                    Mathf.Clamp(newPosition.z, boundsPosition.z - bounds.z, boundsPosition.z + bounds.z));
                cameraTransform.position = Vector3.SmoothDamp(cameraTransform.position, newPosition,  ref current, .5f);
            }

            if (Input.GetMouseButtonUp(0))
            { 
                desc = LeanTween.move(gameObject, boundsPosition, .5f).setEase(LeanTweenType.linear);
                
            }
        }

        private void OnDrawGizmos()
        {
            Gizmos.DrawWireCube(transform.position, bounds);
        }
    }

}